from django import forms
from django.db import transaction
from django.http import JsonResponse
from django.views.generic import View

from main.decorators import require_username, validate_input, check_object_id
from main.models import Subscription
from main.responses import *


class SubscriptionMessages(View):
    @check_object_id(Subscription.enabled, 'subscription')
    @require_username
    def get(self, request, subscription):
        """
        当前公众号已发送的消息

        :return:
            count: 消息总数
            list: 消息列表
                id: 公众号ID
                name: 公众号名称
                content: 消息内容
                create_time: 消息发送时间
        """
        if request.user != subscription.owner:
            return Http403('recent user ha not authority')
        
        result = subscription.follower_records.all()
        if not result :
            c = 0
            l = []
            return JsonResponse({'count': c, 'list': l})

        follower = result[0].follower
        qs = subscription.user_messages.filter(user=follower)
        c = qs.count()
        l = [{'id': r.subscription.id,
              'name': r.subscription.name,
              'content': r.content,
              'create_time': r.create_time} for r in qs]
        return JsonResponse({'count': c, 'list': l})

    post_dict = {'content': forms.CharField(max_length=256)}

    @check_object_id(Subscription.enabled, 'subscription')
    @require_username
    @validate_input(post_dict)
    @transaction.atomic
    def post(self, request, subscription, content):
        """
        公众号向所有关注者发送消息

        """
        if request.user != subscription.owner:
            return Http403('recent user ha not authority')

        qs = subscription.follower_records.all()
        if not qs:
            return Http403('you have not follower')

        for q in qs:
            msg = subscription.user_messages.create(user=q.follower,
                                                    content=content)
            msg.save()
        return Http200()


class SubscriptionMessage(View):
    @require_username
    def get(self, request):
        """
        与当前用户相关的消息

        :return:
            count: 消息总数
            list: 消息列表
                id: 公众号ID
                name: 公众号名称
                content: 消息内容
                create_time: 消息发送时间
        """
        qs = request.user.subscription_messages.all()
        c = qs.count()
        l = [{'id': r.subscription.id,
              'name': r.subscription.name,
              'content': r.content,
              'create_time': r.create_time} for r in qs]
        return JsonResponse({'count': c, 'list': l})
